package com.shen.pc;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 精准通知 Condition具有多路通知功能，可以指定通知某个线程
 */
public class JucOrderPC {
    public static void main(String[] args) {
        Data03 data=new Data03();
        new Thread(
                ()->{
                    for (int i = 0; i < 10; i++) {
                        data.printA();
                    }
                }
                ,"A"  ).start();

        new Thread(
                ()->{
                    for (int i = 0; i < 10; i++) {
                        data.printB();
                    }
                }
                ,"B"  ).start();
        new Thread(
                ()->{
                    for (int i = 0; i < 10; i++) {
                        data.printC();
                    }
                }
                ,"C"  ).start();

        /**
         * A在执行！ number===>1
         * B在执行！number===>2
         * C在执行！number===>3
         * A在执行！ number===>1
         * B在执行！number===>2
         * C在执行！number===>3
         * A在执行！ number===>1
         * B在执行！number===>2
         */
    }
}


//判断 等待 业务 通知
class Data03{
    final Lock lock=new ReentrantLock();
    final Condition conditionA = lock.newCondition();
    final Condition conditionB = lock.newCondition();
    final Condition conditionC = lock.newCondition();

    private int number=1;  //1-A 2-B 3-C

    public void printA(){
        lock.lock();//上锁

        try {
            //判断
            while (number!=1){
                //等待
                conditionA.await();
            }
            //业务
            System.out.println(Thread.currentThread().getName()+"在执行！ number===>"+number);
            number=2;
            //通知 指定线程B
            conditionB.signal();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//解锁
        }
    }
    public void printB(){
        lock.lock();//上锁

        try {
            //判断
            while (number!=2){
                conditionB.await();  //等待
            }
            //业务
            System.out.println(Thread.currentThread().getName()+"在执行！number===>"+number);
            number=3;
            //通知 精准通知C
            conditionC.signal();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//解锁
        }
    }
    public void printC(){
        lock.lock();//上锁
        try {
            //判断
            while (number!=3){
                conditionC.signal();  //等待
            }
            //业务
            System.out.println(Thread.currentThread().getName()+"在执行！number===>"+number);
            number=1;
            //通知
            conditionA.signal();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//解锁
        }
    }
}